<template>
  <ContentWrap>
    <div class="device-config-container">
      <div class="config-header">
        <h2 class="config-title">设备配置中心</h2>
        <p class="config-description">在这里您可以管理所有设备的心跳间隔和离线阈值等配置</p>
      </div>
      
      <el-card class="config-card" v-loading="loading">
        <template #header>
          <div class="card-header">
            <span class="header-title">系统配置</span>
            <el-button 
              type="primary" 
              plain 
              size="small"
              @click="handleSave"
              :loading="saveLoading"
              v-if="hasPermi(['yunkong:device-config:update'])"
            >
              <Icon icon="ep:check" class="mr-5px" /> 保存配置
            </el-button>
          </div>
        </template>
        
        <div class="config-form">
          <el-form 
            :model="configData" 
            label-position="top" 
            ref="configFormRef"
          >
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="工作心跳间隔 (秒)" prop="activeHeartbeatInterval">
                  <el-input-number 
                    v-model="configData.activeHeartbeatInterval" 
                    :min="5" 
                    :max="300"
                    class="w-full"
                  />
                  <div class="form-item-help">设备工作状态下发送心跳的时间间隔</div>
                </el-form-item>
              </el-col>
              
              <el-col :span="8">
                <el-form-item label="空闲心跳间隔 (秒)" prop="idleHeartbeatInterval">
                  <el-input-number 
                    v-model="configData.idleHeartbeatInterval" 
                    :min="10" 
                    :max="600"
                    class="w-full"
                  />
                  <div class="form-item-help">设备空闲状态下发送心跳的时间间隔</div>
                </el-form-item>
              </el-col>
              
              <el-col :span="8">
                <el-form-item label="离线阈值 (秒)" prop="offlineThreshold">
                  <el-input-number 
                    v-model="configData.offlineThreshold" 
                    :min="30" 
                    :max="1800"
                    class="w-full"
                  />
                  <div class="form-item-help">超过该时间未收到心跳，设备将被标记为离线</div>
                </el-form-item>
              </el-col>
            </el-row>
            
            <!-- 高级设置（暂时隐藏） -->
            <template v-if="showAdvanced">
              <el-divider content-position="left">高级设置</el-divider>
              
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="资源上报间隔 (分钟)" prop="resourceReportInterval">
                    <el-input-number 
                      v-model="configData.resourceReportInterval" 
                      :min="1" 
                      :max="60"
                      class="w-full"
                    />
                    <div class="form-item-help">设备资源使用情况（CPU、内存等）的上报间隔</div>
                  </el-form-item>
                </el-col>
                
                <el-col :span="12">
                  <el-form-item label="屏幕截图质量 (%)" prop="screenshotQuality">
                    <el-slider 
                      v-model="configData.screenshotQuality" 
                      :min="10" 
                      :max="100"
                      :format-tooltip="value => `${value}%`"
                      show-input
                    />
                    <div class="form-item-help">远程控制时屏幕截图的质量，影响图像清晰度和流量消耗</div>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
            
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input 
                    v-model="configData.remark" 
                    type="textarea" 
                    :rows="2"
                    placeholder="请输入配置备注信息"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-card>
      
      <!-- 配置历史（暂时隐藏） -->
      <el-card v-if="showHistory" class="config-card mt-4">
        <template #header>
          <div class="card-header">
            <span class="header-title">配置历史</span>
            <el-button 
              type="primary" 
              plain 
              size="small"
              @click="showHistory = !showHistory"
            >
              {{ showHistory ? '隐藏历史记录' : '显示历史记录' }}
            </el-button>
          </div>
        </template>
        
        <div v-if="showHistory" class="history-timeline">
          <el-timeline>
            <el-timeline-item
              v-for="(history, index) in configHistory"
              :key="index"
              :timestamp="history.createTime"
              :type="index === 0 ? 'primary' : undefined"
            >
              <el-card class="history-card">
                <div class="history-item">
                  <div class="history-info">
                    <div><strong>修改人：</strong>{{ history.creator }}</div>
                    <div><strong>工作心跳：</strong>{{ history.activeHeartbeatInterval }} 秒</div>
                    <div><strong>空闲心跳：</strong>{{ history.idleHeartbeatInterval }} 秒</div>
                    <div><strong>离线阈值：</strong>{{ history.offlineThreshold }} 秒</div>
                  </div>
                  <div class="history-remark" v-if="history.remark">
                    <strong>备注：</strong>{{ history.remark }}
                  </div>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
        <el-empty v-else description="点击显示历史记录查看配置变更历史" />
      </el-card>
    </div>
  </ContentWrap>
</template>

<script setup lang="ts">
import { DeviceConfigApi, DeviceConfig } from '@/api/yunkong/deviceconfig'

/** 云控设备配置 */
defineOptions({ name: 'DeviceConfig' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(false) // 加载状态
const saveLoading = ref(false) // 保存按钮加载状态
const showHistory = ref(false) // 是否显示历史记录
const showAdvanced = ref(false) // 是否显示高级设置

// 配置数据
const configData = reactive({
  id: 1, // 设置默认ID，避免类型错误
  activeHeartbeatInterval: 30,
  idleHeartbeatInterval: 60,
  offlineThreshold: 180,
  resourceReportInterval: 5,
  screenshotQuality: 80,
  userId: 1, // 设置默认用户ID
  remark: ''
})

// 配置表单引用
const configFormRef = ref()

// 模拟配置历史数据
const configHistory = ref([
  {
    id: 1,
    activeHeartbeatInterval: 30,
    idleHeartbeatInterval: 60,
    offlineThreshold: 180,
    creator: 'admin',
    createTime: '2023-06-15 14:30:00',
    remark: '初始配置'
  },
  {
    id: 2,
    activeHeartbeatInterval: 20,
    idleHeartbeatInterval: 120,
    offlineThreshold: 240,
    creator: 'admin',
    createTime: '2023-06-01 10:15:00',
    remark: '优化心跳配置'
  }
])

/** 获取当前配置 */
const getConfig = async () => {
  loading.value = true
  try {
    const data = await DeviceConfigApi.getDeviceConfig()
    if (data) {
      // 确保ID有值，避免类型错误
      Object.assign(configData, {
        ...data,
        id: data.id || 1,
        userId: data.userId || 1
      })
    }
  } catch (error) {
    console.error('获取配置失败', error)
    message.error('获取配置信息失败')
  } finally {
    loading.value = false
  }
}

/** 保存配置 */
const handleSave = async () => {
  saveLoading.value = true
  try {
    await DeviceConfigApi.updateDeviceConfig(configData as DeviceConfig)
    message.success('配置保存成功')
    
    // 刷新配置
    await getConfig()
    
    // 更新历史记录
    if (showHistory.value) {
      // 这里应该是从后端获取最新的历史记录
      // 这里仅做模拟
      const newHistory = {
        id: configHistory.value.length + 1,
        activeHeartbeatInterval: configData.activeHeartbeatInterval,
        idleHeartbeatInterval: configData.idleHeartbeatInterval,
        offlineThreshold: configData.offlineThreshold,
        creator: 'admin',
        createTime: new Date().toLocaleString(),
        remark: configData.remark
      }
      configHistory.value.unshift(newHistory)
    }
  } catch (error) {
    console.error('保存配置失败', error)
    message.error('保存配置失败')
  } finally {
    saveLoading.value = false
  }
}

/** 检查权限 */
const hasPermi = (perms: string[]) => {
  return true // 实际项目中应该使用权限检查函数
}

/** 初始化 **/
onMounted(() => {
  getConfig()
})
</script>

<style lang="scss" scoped>
.device-config-container {
  max-width: 1200px;
  margin: 0 auto;
  
  .config-header {
    text-align: center;
    margin-bottom: 24px;
    
    .config-title {
      font-size: 24px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 8px;
    }
    
    .config-description {
      color: var(--el-text-color-secondary);
      font-size: 14px;
    }
  }
  
  .config-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-title {
        font-size: 16px;
        font-weight: 600;
      }
    }
    
    .config-form {
      padding: 10px 0;
      
      .form-item-help {
        font-size: 12px;
        color: var(--el-text-color-secondary);
        margin-top: 4px;
      }
    }
  }
  
  .history-timeline {
    padding: 10px 0;
    
    .history-card {
      --el-card-padding: 12px;
    }
    
    .history-item {
      .history-info {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 8px;
        margin-bottom: 8px;
      }
      
      .history-remark {
        margin-top: 8px;
        padding-top: 8px;
        border-top: 1px dashed var(--el-border-color-lighter);
      }
    }
  }
}

.w-full {
  width: 100%;
}

.mt-4 {
  margin-top: 16px;
}
</style>